package iscte.ai.kcgtd;

import iscte.ai.kcgtd.GridviewAdapter.ViewHolder;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	public static final String CATEGORIA_PROJECTOS = "Projectos";
	public static final String CATEGORIA_LAZER = "Lazer";
	public static final String CATEGORIA_COMPRAS = "Compras";
	public static final String[] CATEGORIAS= {CATEGORIA_PROJECTOS, CATEGORIA_LAZER, CATEGORIA_COMPRAS};

	private static final int CREATE_NEW_TASK = 0;
	private static final int VIEW_TASKS = 1;
	private static final int CALENDAR = 2;
	private static final int STATISTICS = 3;
	private static final int SCHEDULE_MINUTES = 2;

	protected static DatabaseHandler db;
	protected static Settings settings;
	protected static boolean printName;
	protected static ArrayList<Task> projectos;
	protected static ArrayList<Task> lazer;
	protected static ArrayList<Task> compras;

	private String WelcomeString = "Bem Vindo, ";
	private ArrayList<String> options;
	private ArrayList<Integer> optionsIcons;

	private GridviewAdapter mAdapter;
	private TextView welcomeText;
	private SharedPreferences prefs;

	private Button test;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		db = new DatabaseHandler(this);

		prepareList();
		loadData();

		welcomeText = (TextView) findViewById(R.id.welcomeText);

		// prepared arraylist and passed it to the Adapter class
		mAdapter = new GridviewAdapter(this, options, optionsIcons);

		// Set custom adapter to gridview
		GridView gridView = (GridView) findViewById(R.id.gridView);
		gridView.setPadding(0, 120, 0, 0);
		gridView.setAdapter(mAdapter);

		// Implement On Item click listener
		gridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapter, View arg1, int position, long arg3) {
				Intent intent;

				switch(position){
				case CREATE_NEW_TASK:
					intent = new Intent("android.intent.action.CreateNewTask");
					startActivity(intent);

					break;

				case VIEW_TASKS:
					intent = new Intent("android.intent.action.SeeCategories");
					startActivity(intent);

					break;	

				case CALENDAR:
					intent = new Intent(MainActivity.this,CalendarActivity.class);
					startActivity(intent);
					break;	

				case STATISTICS:

					break;
				}


			}
		});

		LinearLayout alertsLayout = (LinearLayout) findViewById(R.id.alertsLayout);
		fillAlertsLayout(alertsLayout);

		alertsLayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Toast.makeText(MainActivity.this, "Alerts", Toast.LENGTH_SHORT).show();
			}
		});

		prefs = PreferenceManager.getDefaultSharedPreferences(this);
		if(prefs.getBoolean("firstTime", true)) {
			Intent intent = new Intent(this,FirstTime.class);
			this.startActivity(intent);
		}else{
			welcomeMessage();
			printName = false;
		}

		test = (Button) findViewById(R.id.button1);
		test.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, Suggestion.class);
				startActivity(intent);
			}
		});

	}

	private void welcomeMessage() {
		settings = db.getSettings();
		WelcomeString += settings.getFirstName() + " " +  settings.getLastName();
		welcomeText.setText(WelcomeString);
	}

	private void loadData() {
		Bag bag = Utils.loadData(this);
		if(bag == null){
			projectos = new ArrayList<Task>();
			lazer = new ArrayList<Task>();
			compras = new ArrayList<Task>();

		}else{

			if(bag.getProjectos() == null){
				projectos = new ArrayList<Task>();
			}else{
				projectos = bag.getProjectos();
			}

			if(bag.getLazer() == null){
				lazer = new ArrayList<Task>();
			}else{
				lazer = bag.getLazer();
			}

			if(bag.getCompras() == null){
				compras = new ArrayList<Task>();
			}else{
				compras = bag.getCompras();
			}
			
			Statistics.IM = bag.getIM();
			Statistics.FM = bag.getFM();
			Statistics.IT = bag.getIT();
			Statistics.FT = bag.getFT();
			Statistics.IN = bag.getIN();
			Statistics.FN = bag.getFN();
			
		}

	}

	@Override
	protected void onRestart() {
		super.onRestart();

		if(FirstTime.forceExit){
			this.finish();
		}

		if(printName){
			welcomeMessage();
			printName = false;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		prefs = PreferenceManager.getDefaultSharedPreferences(this);
		if(prefs.getBoolean("scheduleTime", true)) {
			//Quando o utilizador abre a aplicação é agendada uma calendarização dentro de 2 minutos.
			Utils.createScheduledNotification(MainActivity.this, false, SCHEDULE_MINUTES);
			SharedPreferences.Editor editor = prefs.edit();
			editor.putBoolean("scheduleTime", false);
			editor.commit();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	public void prepareList() {
		options = new ArrayList<String>();
		options.add("Criar Objectivo");
		options.add("Ver Objectivos");
		options.add("Calendário");
		options.add("Estatísticas");

		optionsIcons = new ArrayList<Integer>();
		optionsIcons.add(R.drawable.create_new_task);
		optionsIcons.add(R.drawable.view_tasks);
		optionsIcons.add(R.drawable.calendar);
		optionsIcons.add(R.drawable.statistics);
	}

	public void fillAlertsLayout(LinearLayout alertsLayout){
		ViewHolder view = new ViewHolder();
		View convertView = this.getLayoutInflater().inflate(R.layout.alertslayout_row, null);

		view.txtViewTitle = (TextView) convertView.findViewById(R.id.textView);
		view.txtViewTitle.setText("Alertas");

		view.imgViewFlag = (ImageView) convertView.findViewById(R.id.imageView);
		view.imgViewFlag.setImageResource(R.drawable.alerts);

		alertsLayout.addView(convertView);
	}

}
